import os
import sys
import logging
import logging.handlers
import getopt

log = None
settings = { 'tmpdir' : '/tmp/wxdaemon/', 'port' : 8000, 'bindir' : '', 'debug' : 0 }

def usage():
	print('-d --debug    -- enable debugging (Do not redirect linkbacks)')
	print('-h --help     -- print help')

def init():
	try:
		opts, args = getopt.getopt(sys.argv[1:], "hd", ["help", "debug"])
	except getopt.GetoptError:
		usage()
		sys.exit(2)      
		
	for opt, arg in opts:
		if opt in ("-d", "--debug"):
			settings['debug'] = 1
		elif opt in ("-h", "--help"):
			usage()
			sys.exit(1)

	settings['bindir'] = os.getcwd()
	print('bindir:' + settings['bindir'])
	
	if not os.path.exists(settings['tmpdir']):
		os.mkdir(settings['tmpdir'])
		
	os.chdir(settings['tmpdir'])

	log = logging.getLogger('logger')
	log.setLevel(logging.INFO)
	handler = logging.handlers.RotatingFileHandler('wxd.log', maxBytes = 1000000, backupCount = 5)
	formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
	handler.setFormatter(formatter)
	log.addHandler(handler)
	log.addHandler(logging.StreamHandler(sys.stdout))
	
	return log

if log == None:
	log = init()
